package com.hedl.practice.diyJava.multithreading.thread_pool.completable_future.test;

import java.util.concurrent.CompletableFuture;

public class StudyCompletableFuture_2 {

    public static void main(String[] args) throws InterruptedException {
        //第一个任务
        CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(()->{     //步骤一
            return queryCode("中国石油");       //拿到石油代码
        });

        //cfQuery成功后继续执行下个任务
        //thenApplyAsync()是继承与CompletionStage<T>接口
        CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code)->{        //code是查取到的股票代码601857；步骤三
            return fetchPrice(code);        //用股票代码查股票价格
        });

        cfFetch.thenAccept((result)->{
            System.out.println("price: "+result);
        });
        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(2000);
    }

    static String queryCode(String name){       //步骤二
        try{
            Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        return "601857";
    }

    static Double fetchPrice(String code){      //步骤四
        try{
            Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        return 5 + Math.random() * 20;
    }
}
